const ClientAlias = {
  EMI_CLIENT    : 'emi_client',
  IAVIA_CLIENT : 'iqvia_client',
  RECONTACT_CLIENT : 'recontact_client',
  AUDIENCE_ALIGN : 'audience_align',
  SUPPLIER_PURE_SPECTRUM : 'supplier_ps',
  REP_DATA : 'supplier_rep',
  SUPPLIER_SYMMETRIC_SAMPLING : 'supplier_symmetric',
  SUPPLIER_CATALYSE_RESEARCH : 'supplier_catalyse',
  UNIMRKT : 'supplier_unimrkt',
  SUPPLIER_SAGO : 'supplier_sago',
  MR_TECH_OPS : 'mr_tech_ops',
  GOOD_HUMAN_PARTNERS : 'good_human_partners',
  RUSSELL_RESEARCH : 'russell_research',
  GREAT_BLUE_RESEARCH : 'great_blue_research',
  CINT_AB : 'cint_ab',
  CINT_API : 'cint_api',
  CINT_AU : 'cint_australia',
  CINT_DEUSTCHLAND : 'cint_deutschland',
  CINT_JAPAN : 'cint_japan',
  CINT_EUROPE : 'cint_southern_europe',
  CINT_USA : 'cint_usa',
  CAPGEMINI: 'capegemini',
  CAPGEMINI_ANNIK_INC : 'capegemini_annik_inc',
  DYNATA_LLC : 'dynata_llc',
  DYNATA_LLC_SSI : 'dynata_llc_ssi',
  IPSOS : 'ipsos_interactive_services',
  IPSOS_CA : 'ipsos_interactive_partnership_canada',
  IPSOS_SRL : 'ipsos_interactive_srl',
  AZURE : 'azure',
  BORDERLESS : 'borderless',
  ALLIGATOR_RESEARCH  :'alligator_research',
  DECISION_ANALYST_INC : 'decision_analyst_inc',
  MINDFORCE_RESEARCH :'mindforce_research',
  SOAPBOX_SAMPLE : 'soapbox_sample',
  GLOBAL_RESEARCH_LLC : 'global_research_llc',
  PROGRESSO_RESEARCH_LLC : 'progresso_research_llc',
  ALWAYS_ENABLE_RD_SECURITY:'always_enable_rd_client',
  MARKET_KNOWLEDGE_ONLINE:'tanzola',
  CENSUSWIDE :'censuswide', //add
  PRECISION_SAMPLE:'precision_sample', //add alias
  POTLOC :'potloc', //add
  IHEART_MEDIA : 'iheart_media',
  MORESCODE :'morescode', //ADD
  PURE_PROFILE:'pure_profile',
  BILENDI :'bilendi',
  EOL :'eol',
  MEDIA_GROUP : '4media_group',
  H_P : 'hall_partners',
  DIPSTICKS_RESEARCH_LIMITED :'dipsticks',
  INTERNET_RESEARCH_BUREAU : 'internet_research_bureau',
  DATAXING_DIGITAL : 'dataxing_digital',
  TORFAC_CANADA : 'torfac_canada',
  MENA_OPINION_RESEARCH : 'mena_opinion_research',
  PANEL_VIEW_POINT : 'panel_view_point',
  TEST_SET: 'test_set'
}

const ProjectTypes = {
  B2B: 1,
  B2C: 2,
  MEDICAL: 3,
  PII: 4,
  NA: 5
};

const ELRID_PREFIX = 'ELR00';

const VendorAlias = {
  FALCRUM:        'ful',
  PURE_SPECTRUM:  'ps',
  THEOREM_REACH:  'theorem',
  CINT:           'cint',
  DISQO:          'dis',
  DYNATA:         'dynata',
  ANASKA:         'anaska',
  NORMAL_FULCRUM: 'normal-ful',
  p2SOLO:         'p2solo',
  NORMAL_DYNATA:  'normal-dynata',
  OPINIO_QUEST:   'opinio_quest',
  MAKE_OPINION:   'make_opinion',
  PEANUT_LAB:     'peanutlab',
  SOLOGU:         'sologu',
  RFG:            'rfg',
  SAGO:           'sago',
  CINT_NORMAL_DIY: 'cint_normal_diy',
  ZAMPLIA_NON_API: 'zamplia_non_api',
};

const SurveyStatus = {
  ABANDON: 1,
  DISQUALIFIED: 2,
  QUOTAFULL: 3,
  DUPLICATE_IP: 4,
  COMPLETED: 5,
  DUPLICATE_PID: 6,
  DIFFERENT_COUNTRY: 7,
  FAILED_AT_PRE_SCREENING: 8,
  LOI_EXCEED: 9,
  SPEEDER: 10,
  INVALID_UNIQUE_LINK: 11,
  QUALITY_TERMINATE: 12,
  IN_SURVEY: 13,
  BLOCKED_BY_RD: 14,
  RD_ACTIVITY_FAIL: 15,
  RD_SEARCH_FAIL: 16,
  RD_REVIEW_FAIL: 17,
  SECURITY_FAIL: 18
};

const RESEARCH_SECURITY_CONST = {
  RESEARCH_DEFENDER_FRAUD_SCORE: 28,
  RESEARCH_DEFENDER_HIGH_SECURITY_FRAUD_SCORE: 20,
  // Activity API Details
  RD_ACTIVITY_URL: 'https://prod.resdefio.com/activity',
  RD_ACTIVITY_TOKEN_COUNT: 50,
  // Token API Details
  RESEARCH_DEFENDER_TOKEN_API_URL: "https://prod.rtymgt.com/api/v3/respondents/get_token/ac81b20f-1f54-4dbc-b1e8-468a691a1486",
  // Client list
  RD_SECURITY_ENABLED_CLIENT: [
      ClientAlias.REP_DATA,
      ClientAlias.MR_TECH_OPS,
      ClientAlias.GOOD_HUMAN_PARTNERS,
      ClientAlias.RUSSELL_RESEARCH,
      ClientAlias.GREAT_BLUE_RESEARCH,
      ClientAlias.EMI_CLIENT,
      ClientAlias.ALWAYS_ENABLE_RD_SECURITY
  ],
  REPDATA_RD_FRAUD_SCORE: 32
};

class RDApiLogs {
  constructor() {
      this.projectId = "";
      this.surveyAttemptID = 0;
      this.respondentId = "";
      this.logType = "";
      this.request = null;
      this.response = null;
      this.activityCeUd = undefined;  // Optional properties can be undefined initially
      this.activityResponse = undefined;
      this.v3Token = undefined;
      this.tokenTime = undefined;
  }
}

const ApisVendorsList = [
  VendorAlias.FALCRUM,
  VendorAlias.DYNATA,
  VendorAlias.DISQO,
  VendorAlias.PURE_SPECTRUM,
  VendorAlias.THEOREM_REACH,
  VendorAlias.CINT,
  VendorAlias.SAGO
];

const SuppliersList = [
  ClientAlias.SUPPLIER_PURE_SPECTRUM,
  ClientAlias.REP_DATA,
  ClientAlias.SUPPLIER_SYMMETRIC_SAMPLING,
  ClientAlias.SUPPLIER_SAGO,
  ClientAlias.UNIMRKT,
  ClientAlias.SUPPLIER_CATALYSE_RESEARCH
];

const UnimrktQuestionConst = {
  Age: "1001",
  Gender: "1002",
  PostalCode: {
      231: "1085", // United States
      230: "1194", // United Kingdom
      11: "1193", // Australia
      36: "1113", // Canada
      99: "1125", // India
  }
};

const PureSpectrumQuestionConst = {
  Age: "212",
  Gender: "211",
  PostalCode: "229",
  HouseholdIncome: "213",
};

const RepDataQuestionConst = {
  Age: "42",
  Gender: "43",
  PostalCode: "45",
};

const SymmetricQuestionConst = {
  Age: "59",
  Gender: "60",
  PostalCode: "143",
  HouseholdIncome: "4454",
};

const CatalyseQuestionConst = {
  Age: "2",
  Gender: "6",
  PostalCode: "13",
  // HouseholdIncome: "75",
};

const SagoQuestionConst = {
  Age: "age",
  Gender: "gender",
  PostalCode: "zipCode",
};

class QualificationsConstants {
  static AGE_SLUG = 'age';
  static HOUSEHOLD_INCOME_SLUG = 'HouseholdIncome';
  static POSTCODE_SLUG = 'postcode';
  static HHI_OTHER_OPTION_TITLE = 'Other';
  static HHI_LT_5000 = 'Less than 5,000';
  static HHI_GT_250000 = '250,000 and above';
  static GENDER_SLUG = 'Gender';
}

const PrescreenerClients = [
  // ClientAlias.TEST_SET
];

// kk
let kkMin = localStorage.getItem('kk-min') || 10
console.log('kkMin: ', kkMin);
let kkMax = localStorage.getItem('kk-max') || 15
console.log('kkMax: ', kkMax);
function getRandomIntInRange(min=kkMin, max=kkMax) {
  if (min > max) {
      throw new Error('min should be less than or equal to max');
  }
  return Math.floor(Math.random() * (max - min + 1)) + min;
}


// 保存原始的 fetch 方法
const originalFetch = window.fetch;

// 重写 fetch 方法
window.fetch = async function (...args) {
  try {
    const [resource, config] = args;

    // 发送原始请求
    const response = await originalFetch.apply(this, args);

    // 检查 response 是否有效
    if (!response || !response.ok) {
      console.error('请求失败:', response.status, response.statusText);
      return response; // 返回原始 response
    }

    // 只处理特定 URL
    if (response.url && response.url.includes('https://prod.rtymgt.com/api/v3/respondents/search')) {
      let clonedResponse = response.clone(); // 克隆 response 以防止 body 被提前读取
      let data;

      try {
        data = await clonedResponse.json(); // 解析 JSON
        console.log('data: ', data);
      } catch (error) {
        console.error('JSON 解析失败:', error);
        return response; // 解析失败则直接返回原始 response
      }

      // 修改数据
      if (data && data.Respondent) {
        data.Respondent.respondent_risk = 0;
        data.Respondent.threat_potential = 'low';
        data.Respondent.threat_potential_score = getRandomIntInRange();
      }

      // 重新构造 response，确保 headers 也被正确设置
      return new Response(JSON.stringify(data), {
        status: response.status,
        statusText: response.statusText,
        headers: new Headers(response.headers), // 复制原 headers
      });
    }

    if (response.url && response.url.includes('https://prod.rtymgt.com/api/v4/respondents/review')) {
      let clonedResponse = response.clone(); // 克隆 response 以防止 body 被提前读取
      let data;

      try {
        data = await clonedResponse.json(); // 解析 JSON
        console.log('data: ', data);
      } catch (error) {
        console.error('JSON 解析失败:', error);
        return response; // 解析失败则直接返回原始 response
      }

      // 修改数据
      const reviewScore = data.results[0]?.score;
      if (data && reviewScore) {
        reviewScore.composite_score = 0
        reviewScore.similarity_text = 0
      }

      // 重新构造 response，确保 headers 也被正确设置
      return new Response(JSON.stringify(data), {
        status: response.status,
        statusText: response.statusText,
        headers: new Headers(response.headers), // 复制原 headers
      });
    }

    return response;
  } catch (error) {
    console.error('fetch 拦截错误:', error);
    return originalFetch.apply(this, args); // 遇到错误时调用原始 fetch
  }
};
